package com.lee.demo.videocompress.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.VideoAttributes;

import java.io.File;
import java.util.Base64;

/**
 * 视频处理
 * @author lyq
 * @time 2019/6/25 20:37
 */
@RestController
@Slf4j
public class VideoController {

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception{
        long startTime = System.currentTimeMillis();
        log.info("收到的视频大小：{}MB",file.getSize()/1024/1024.0);
        File source = new File("d:/2.mp4");
        File target = new File("d:/3.mp4");
        file.transferTo(source);

        //音频
        AudioAttributes audio= new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(128000);
        audio.setChannels(1);
        audio.setSamplingRate(44100);

        //视频
        VideoAttributes video=new VideoAttributes();
        video.setCodec("mpeg4");
        video.setBitRate(360000);
        video.setFrameRate(15);

        //转码配置
        EncodingAttributes attr=new EncodingAttributes();
        attr.setFormat("mp4");
        attr.setAudioAttributes(audio);
        attr.setVideoAttributes(video);

        //转码
        Encoder encoder=new Encoder();
        encoder.encode(new MultimediaObject(source), target, attr);

        //文件转base64
        byte[] bytes = FileCopyUtils.copyToByteArray(target);
        String base64Str = Base64.getEncoder().encodeToString(bytes);
        source.delete();
        target.delete();

        //测试转出来的字符串能不能变成视频
        File outFile = new File("d:/4.mp4");
        FileCopyUtils.copy(Base64.getDecoder().decode(base64Str),outFile);

        long stopTime = System.currentTimeMillis();
        log.info("耗时：{}ms",stopTime - startTime);
        return "success";
    }
}
